package com.hh;

import java.io.*;

/**
 * 序列化与反序列化破坏单例模式
 */
public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Singleton s=Singleton.getInstance();
        Test.write(s);
        Singleton s1=Test.read();
        Singleton s2=Test.read();
        System.out.println(s1==s2);//结果为false
        //加readResolve方法后此时结果就为true


    }
    //把对象转成字节数据的输出到文件中保存，把对象进行序列化
    public static void write(Singleton s) throws IOException {
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("e:/s/c.txt"));
        oos.writeObject(s);
        oos.close();
    }
    //把对象进行反序列化
    public static  Singleton read() throws IOException, ClassNotFoundException {
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("e:/s/c.txt"));
        Singleton singleton=(Singleton)ois.readObject();
        ois.close();
       return singleton;
    }

}
